package club.web51.classroom_tool.Controllers;

import club.web51.classroom_tool.DO.collDO.Academy;
import club.web51.classroom_tool.DO.collDO.Clazz;
import club.web51.classroom_tool.DO.sysDO.Msg;
import club.web51.classroom_tool.Enums.MsgEnum;
import club.web51.classroom_tool.Exceptions.ErrDataException;
import club.web51.classroom_tool.Services.ClazzService;
import club.web51.classroom_tool.Utils.MsgUtil;
import club.web51.classroom_tool.Utils.ObjectUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Objects;

/**
 * 服务类
 * @author Hanyuhao
 * @since 1.0.0
 */
@RestController
@CrossOrigin
@RequestMapping("/clazz")
@Api(value = "班级模块",tags={"班级操作接口"})

public class ClazzController {

    final
    ClazzService clazzService;

    public ClazzController(ClazzService clazzService) {
        this.clazzService = clazzService;
    }

    /**
     * 根据Clazz的字段,自动生成条件,字段的值为null不生成条件
     * http://localhost:8080/user/?id=1
     * @param clazz 实体对象
     * @param pageable 分页/排序对象
     * @return 返回的是实体,里面涵盖分页信息及状态码
     */
     @GetMapping
     @ApiOperation(value = "动态查询，可输入对应对象的一个或多个属性",notes = "全体用户均有权限",httpMethod = "GET")
     @RequiresPermissions(logical = Logical.OR, value = {"1","2", "3"})
     ResponseEntity<Object> search(Clazz clazz, Pageable pageable) {
             return clazzService.search(clazz, pageable);
     }
    @PostMapping
    @ApiOperation("创建班级")
    @RequiresPermissions(logical = Logical.OR, value = {"2", "3"})
    Msg create(@RequestBody @Valid Clazz clazz, BindingResult bindingResult) {
        if(bindingResult.hasErrors()){
            throw new ErrDataException(Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
        }
        clazz.setId(null);
        clazzService.updateOne(clazz);
        return MsgUtil.success();
    }
    @PutMapping
    @ApiOperation("修改班级")
    @RequiresPermissions(logical = Logical.OR, value = {"2", "3"})
    Msg update(@Valid Clazz clazz,BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            throw new ErrDataException(Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
        }
        if(ObjectUtil.isNull(clazz.getId()))
            throw new ErrDataException(MsgEnum.ERROR_DATA_EMPTY);
        clazzService.updateOne(clazz);
        return MsgUtil.success();
    }
    @DeleteMapping("/")
    @ApiOperation("删除班级，输入ID")
    @RequiresPermissions(logical = Logical.OR, value = {"2", "3"})
    Msg delete(Long id){
        clazzService.deleteOne(id);
        return MsgUtil.success();
    }
}
